package com.cx.controller.fhy;

import com.cx.config.RequestResult;
import com.cx.constant.ConstantData;
import com.cx.pojo.Game;
import com.cx.pojo.ResultData;
import com.cx.pojo.User;
import com.cx.service.fhy.GameService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("publishgame")
@SessionAttributes(names = {"gameId"}, types = {Game.class})
public class PublishGameController {
    @Autowired
    private GameService gameService;

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        //只要网页中传来的数据格式为yyyy-MM-dd 就会转化为Date类型
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    @RequestMapping("publishgame")
    @ResponseBody
    public void publishGame(HttpSession session, @RequestParam("gamePicture") MultipartFile file, @RequestParam("gameBody") MultipartFile file2, HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = (User) session.getAttribute(ConstantData.SESSION_KEY);
        Integer userId = user.getUserId();

        String fileName =  UUID.randomUUID() +file.getOriginalFilename();
        String filePath="C:\\Users\\fhy\\IdeaProjects\\gamemall2\\gamemall-web\\src\\main\\webapp\\gamepicture\\";
        File dest=new File(filePath+fileName);

        String file2Name = UUID.randomUUID() + file2.getOriginalFilename();
        String file2Path="C:\\Users\\fhy\\IdeaProjects\\gamemall2\\gamemall-web\\src\\main\\webapp\\gamebody\\";
        File dest2=new File(file2Path+file2Name);

        String gameName =  request.getParameter("gameName");
        Long gamePrice = Long.valueOf(request.getParameter("gamePrice"));
        String gameIntroduction = request.getParameter("gameIntroduction");
        String gamePicture = "http://localhost:8081/img/" + fileName;
        Integer gtId = Integer.valueOf(request.getParameter("gtId"));
        Long gameDiscount = Long.valueOf(request.getParameter("gameDiscount"));
        String gameBody = "http://localhost:8081/body/" + file2Name;
        Date gameTime = new Date();
        Game game = new Game();
        game.setGameName(gameName);
        game.setGamePrice(gamePrice);
        game.setUserId(userId);
        game.setGameIntroduction(gameIntroduction);
        game.setGamePicture(gamePicture);
        game.setGtId(gtId);
        game.setGameDiscount(gameDiscount);
        game.setGameBody(gameBody);
        game.setGameTime(gameTime);
        RequestResult requestResult = null;
        int affectedRows = gameService.publishgame(game);
        if (affectedRows > 0){
            file.transferTo(dest);
            file2.transferTo(dest2);
            requestResult=new RequestResult(1,"发布成功",null);
        }else {
            requestResult=new RequestResult(2,"发布失败",null);
        }
        response.getWriter().write(new Gson().toJson(requestResult));
    }


    @RequestMapping(value = "updategame")
    @ResponseBody
    public void updateGame(@RequestParam(name="gamePicture", required = false) MultipartFile file, @RequestParam(name="gameBody", required = false) MultipartFile file2, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String gamePicture = null;
        String gameBody = null;

        if(null == file){
            gamePicture = null;
        }else {
            String fileName = UUID.randomUUID() + file.getOriginalFilename();
            String filePath = "C:\\Users\\fhy\\IdeaProjects\\gamemall2\\gamemall-web\\src\\main\\webapp\\gamepicture\\";
            File dest = new File(filePath + fileName);
            gamePicture = "http://localhost:8081/img/" + fileName;
            file.transferTo(dest);
        }

        if(null == file2){
            gameBody = null;
        }else {
            String file2Name =  UUID.randomUUID() + file2.getOriginalFilename();
            String file2Path="C:\\Users\\fhy\\IdeaProjects\\gamemall2\\gamemall-web\\src\\main\\webapp\\gamebody\\";
            File dest2=new File(file2Path+file2Name);
            gameBody = "http://localhost:8081/body/" + file2Name;
            file2.transferTo(dest2);
        }

        Integer gameId = Integer.valueOf(request.getParameter("gameId"));
        String gameName =  request.getParameter("gameName");
        Long gamePrice = Long.valueOf(request.getParameter("gamePrice"));
        String gameIntroduction = request.getParameter("gameIntroduction");
        Integer gtId = Integer.valueOf(request.getParameter("gtId"));
        Long gameDiscount = Long.valueOf(request.getParameter("gameDiscount"));


        Game game = new Game();
        game.setGameId(gameId);
        game.setGameName(gameName);
        game.setGamePrice(gamePrice);
        game.setGameIntroduction(gameIntroduction);
        game.setGamePicture(gamePicture);
        game.setGtId(gtId);
        game.setGameDiscount(gameDiscount);
        game.setGameBody(gameBody);
        RequestResult requestResult = null;
        int affectedRows = gameService.updategame(game,gameId);
        if (affectedRows > 0){
            requestResult=new RequestResult(1,"发布成功",null);
        }else {
            requestResult=new RequestResult(2,"发布失败",null);
        }
        response.getWriter().write(new Gson().toJson(requestResult));
    }

    @RequestMapping("selectByUserId")
    @ResponseBody
    public List<Game> selectByUserId(HttpSession session){
        User user = (User) session.getAttribute(ConstantData.SESSION_KEY);
        String userId = String.valueOf(user.getUserId());
        List<Game> games=gameService.selectByUserId(userId);
        return games;
    }

    @RequestMapping("deletegame")
    @ResponseBody
    public void deleteGame(Integer gameId, HttpServletResponse response) throws IOException {
        int deleteFieldNum = gameService.deletegame(gameId);
        if (deleteFieldNum > 0) {
            response.sendRedirect("/mypublishgame.jsp");
        } else {
            response.sendRedirect("/mypublishgame.jsp");
        }
    }

    @RequestMapping("transmitgame")
    public String transmitGame(Integer gameId,HttpSession session) throws IOException {
        Game game = gameService.selectByGameId(gameId);
        session.setAttribute("game",game);
        return "forward:/updategame.jsp";

    }
}